package com.ybkj.daijia.api.weixin.handler.impl;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.WxSetting;
import com.ybkj.daijia.api.weixin.WxMsgType;
import com.ybkj.daijia.api.weixin.entity.WxBaseMsgEntity;
import com.ybkj.daijia.api.weixin.entity.WxBaseRespEntity;
import com.ybkj.daijia.api.weixin.entity.WxItemPicDescEntity;
import com.ybkj.daijia.api.weixin.entity.WxMsgEventEntity;
import com.ybkj.daijia.api.weixin.entity.WxRespPicDescEntity;
import com.ybkj.daijia.api.weixin.entity.WxRespTextEntity;
import com.ybkj.daijia.common.Distance;
import com.ybkj.daijia.common.PageVo;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.WxLocation;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.WxLocationService;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class WxQueryDriverTextHandler extends AbstractWxEventHandler {

    @Autowired
    private WxLocationService wxLocationService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private SettingUtils settingUtils;


    @Override
    public boolean canHandle(WxBaseMsgEntity msg) {
        if (super.canHandle(msg)) {
            if ("drivers".equals(((WxMsgEventEntity) msg).getEventKey())) {
                return true;
            }
        }

        return false;
    }


    @Override
    public WxBaseRespEntity handleEvent(WxMsgEventEntity msg,
        Map<String, Object> context, WxBaseRespEntity resp) {

        WxLocation wxLocation = wxLocationService.findLastedByWxuser(msg.getFromUserName());
        if (null == wxLocation
            || System.currentTimeMillis() - wxLocation.getCreated().getTime() >= 1000 * 60 * 5) {
            //点击我要代驾按钮
            WxRespTextEntity text = new WxRespTextEntity();
            text.setContent(
                "请发送您的位置：\n1、点击左下方“小键盘”；\n2、点击右下方“＋”号键；\n3、点击“位置”图标按钮；\n4、选择自己所在的位置后点击“发送”按钮；\n5、如果未绑定 回复手机号码进行绑定。");
            text.setCreatedDate(new Date());
            text.setCreateTime(text.getCreatedDate().getTime());
            text.setFromUserName(msg.getToUserName());
            text.setToUserName(msg.getFromUserName());
            text.setFuncFlag(0);
            text.setMsgType(WxMsgType.text.name());

            return text;
        } else {
            WxSetting setting = settingUtils.getWx();

            String label = "";
            label = HttpClientUtil
                .getPlaceByLngAndLat(wxLocation.getLongitude(), wxLocation.getLatitude());

            //查询附近的司机
            PageVo<Driver> page = driverService
                .queryNearDrivers(wxLocation.getLongitude(), wxLocation.getLatitude(), 0,
                    9);//附近10条记录
            List<Driver> drivers = page.getContent();

            if (!CollectionUtils.isEmpty(drivers)) {

                WxRespPicDescEntity news = new WxRespPicDescEntity();

                List<WxItemPicDescEntity> articles = new LinkedList<WxItemPicDescEntity>();

                WxItemPicDescEntity item = new WxItemPicDescEntity();
                item.setTitle("附近的服务人员");
                String pic = String
                    .format("%sassets/img/nearby_drivers.png", setting.getWxServer());
                String url = String.format("%s/wx/v1/aboutus", setting.getWxServer());
                item.setPicUrl(pic);
                item.setUrl(url);
                articles.add(item);

                if (StringUtils.isNotBlank(label)) {
                    try {
                        label = URLEncoder.encode(label, "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                for (Driver driver : drivers) {

                    item = new WxItemPicDescEntity();

                    double distance = Distance
                        .doubleVal(wxLocation.getLatitude(), wxLocation.getLongitude(),
                            driver.getLatitude(), driver.getLongitude());

                    DecimalFormat df = new DecimalFormat("0.0");

                    String title = String
                        .format("%s( %s 公里 )", driver.getName(), df.format(distance));
                    pic = String
                        .format("%supload/driver/%s", setting.getWxServer(), driver.getPhoto());

                    url = String.format("%swx/v1/driver/%d?label=%s&lat=%f&lng=%f&t=%d&wxuser=%s",
                        setting.getWxServer(), driver.getId(), label, wxLocation.getLatitude(),
                        wxLocation.getLongitude(), System.currentTimeMillis(), msg.getFromUserName());

                    item.setTitle(title);
                    item.setPicUrl(pic);
                    item.setUrl(url);

                    articles.add(item);
                }

                news.setArticles(articles);
                news.setCreatedDate(new Date());
                news.setCreateTime(news.getCreatedDate().getTime());
                news.setFromUserName(msg.getToUserName());
                news.setToUserName(msg.getFromUserName());
                news.setFuncFlag(0);
                news.setMsgType(WxMsgType.news.name());

                return news;
            } else {
                WxRespTextEntity text = new WxRespTextEntity();
                text.setContent(setting.getWxQueryDriverNoResult());
                text.setCreatedDate(new Date());
                text.setCreateTime(text.getCreatedDate().getTime());
                text.setFromUserName(msg.getToUserName());
                text.setToUserName(msg.getFromUserName());
                text.setFuncFlag(0);
                text.setMsgType(WxMsgType.text.name());

                return text;
            }
        }

    }


}
